<template>
  <div class="order-detail-container">
    <!-- 订单状态 -->
    <div class="status-card">
      <div class="status-header">
        <div class="status-text">
          <el-icon :size="32" :color="getStatusColor(order.status)">
            <component :is="getStatusIcon(order.status)" />
          </el-icon>
          <div class="status-info">
            <h2>{{ getStatusText(order.status) }}</h2>
            <p>{{ getStatusDescription(order.status) }}</p>
          </div>
        </div>
        <div class="status-actions">
          <el-button v-if="order.status === 1" type="primary" @click="handlePay">
            立即付款
          </el-button>
          <el-button v-if="order.status === 3" type="success" @click="handleConfirmReceive">
            确认收货
          </el-button>
          <el-button v-if="order.status === 4" type="primary" plain @click="handleReview">
            评价
          </el-button>
          <el-button v-if="order.status === 1" type="danger" plain @click="handleCancel">
            取消订单
          </el-button>
          <el-button v-if="order.status === 2 || order.status === 3 || order.status === 4" type="warning" plain @click="handleRefund">
            申请退款
          </el-button>
        </div>
      </div>
      <el-steps :active="getStatusStep(order.status)" finish-status="success" class="status-steps">
        <el-step title="提交订单" :description="order.createTime" />
        <el-step title="付款成功" :description="order.payTime" />
        <el-step title="商品发货" :description="order.shipTime" />
        <el-step title="交易完成" :description="order.completeTime" />
      </el-steps>
    </div>

    <!-- 收货信息 -->
    <div class="section-card">
      <h3 class="section-title">收货信息</h3>
      <div class="delivery-info">
        <div class="info-item">
          <span class="label">收货人：</span>
          <span>{{ order.receiver.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系电话：</span>
          <span>{{ order.receiver.phone }}</span>
        </div>
        <div class="info-item">
          <span class="label">收货地址：</span>
          <span>{{ order.receiver.address }}</span>
        </div>
      </div>
    </div>

    <!-- 商品信息 -->
    <div class="section-card">
      <h3 class="section-title">商品信息</h3>
      <el-table :data="order.items" style="width: 100%">
        <el-table-column label="商品信息" min-width="400">
          <template #default="{ row }">
            <div class="product-info">
              <el-image :src="row.mainImage" class="product-image" />
              <div class="product-detail">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-specs">{{ row.specs }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120" align="center">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120" align="center">
          <template #default="{ row }">
            {{ row.quantity }}
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120" align="right">
          <template #default="{ row }">
            <span class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 支付信息 -->
    <div class="section-card">
      <h3 class="section-title">支付信息</h3>
      <div class="payment-info">
        <div class="info-group">
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span>{{ getPaymentMethodText(order.paymentMethod) || '支付宝' }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付时间：</span>
            <span>{{ order.payTime || '-' }}</span>
          </div>
        </div>
        <div class="amount-info">
          <div class="amount-item">
            <span>商品总额：</span>
            <span>¥{{ order.totalAmount }}</span>
          </div>
          <div class="amount-item">
            <span>运费：</span>
            <span>¥{{ order.shipping }}</span>
          </div>
          <div class="amount-item total">
            <span>实付款：</span>
            <span class="price">¥{{ order.payAmount ? order.payAmount.toFixed(2) : '0.00' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="section-card">
      <h3 class="section-title">订单信息</h3>
      <div class="order-info">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span>{{ order.orderId }}</span>
          <el-button link type="primary" @click="copyOrderId">复制</el-button>
        </div>
        <div class="info-item">
          <span class="label">创建时间：</span>
          <span>{{ order.createTime }}</span>
        </div>
        <div class="info-item">
          <span class="label">付款时间：</span>
          <span>{{ order.payTime || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="label">发货时间：</span>
          <span>{{ order.shipTime || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="label">完成时间：</span>
          <span>{{ order.completeTime || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单备注：</span>
          <span>{{ order.note || '无' }}</span>
        </div>
      </div>
    </div>

    <!-- 物流信息 -->
    <div v-if="order.status !== 'pending' && order.status !== 'cancelled'" class="section-card">
      <h3 class="section-title">物流信息</h3>
      <div v-if="order.logistics" class="logistics-info">
        <div class="logistics-header">
          <div class="info-item">
            <span class="label">物流公司：</span>
            <span>{{ order.logistics.company }}</span>
          </div>
          <div class="info-item">
            <span class="label">物流单号：</span>
            <span>{{ order.logistics.trackingNumber }}</span>
            <el-button link type="primary" @click="copyTrackingNumber">复制</el-button>
          </div>
        </div>
        <el-timeline class="logistics-timeline">
          <el-timeline-item v-for="(activity, index) in order.logistics.tracks" :key="index" :timestamp="activity.time">
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <div v-else class="empty-logistics">
        暂无物流信息
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import {
  Clock,
  Wallet,
  Van,
  CircleCheck,
  CircleClose,
  RefreshLeft
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 订单数据
const order = ref({})
const loading = ref(false)

// 获取订单详情
const fetchOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) {
    ElMessage.error('订单ID不能为空')
    router.push('/home/orders')
    return
  }

  loading.value = true
  try {
    const res = await request.get(`/orders/${orderId}`)
    if (res.code === 200) {
      order.value = {
        ...res.data,
        orderId: res.data.orderNo,
        createTime: formatDateTime(res.data.createTime),
        payTime: formatDateTime(res.data.paymentTime), // 修正字段名
        shipTime: formatDateTime(res.data.deliveryTime),
        completeTime: formatDateTime(res.data.receiveTime),
        status: res.data.status,
        // 规范化订单项字段，兼容后端字段名
        items: (res.data.orderItems || []).map(it => ({
          id: it.id,
          name: it.productName || it.name,
          mainImage: it.productImage || it.mainImage,
          price: it.price,
          quantity: it.quantity,
          specs: it.specs || ''
        })),
        receiver: {
          name: res.data.receiverName,
          phone: res.data.receiverPhone,
          address: res.data.receiverAddress
        },
        logistics: {
          company: res.data.deliveryCompany || '顺丰速运',
          trackingNumber: res.data.deliveryNo || '',
          tracks: []
        }
      }
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 状态值转换（数据库状态值转前端状态值）
const getStatusKey = (statusValue) => {
  const statusMap = {
    0: 'pending',    // 待付款
    1: 'paid',       // 已付款
    2: 'shipped',    // 已发货
    3: 'completed',  // 已完成
    4: 'cancelled'   // 已取消
  }
  return statusMap[statusValue] || 'pending'
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已取消',
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '交易完成',
    5: '退款中',
    6: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态描述
const getStatusDescription = (status) => {
  const descMap = {
    0: '订单已取消',
    1: '请尽快完成付款，超时订单将自动取消',
    2: '商家正在处理您的订单，请耐心等待',
    3: '商品已发出，请注意查收',
    4: '交易已完成',
    5: '退款申请处理中，请耐心等待',
    6: '退款已完成'
  }
  return descMap[status] || ''
}

// 获取订单状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    0: CircleClose,
    1: Clock,
    2: Wallet,
    3: Van,
    4: CircleCheck,
    5: RefreshLeft,
    6: CircleCheck
  }
  return iconMap[status] || Clock
}

// 获取订单状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending: '#E6A23C',
    paid: '#409EFF',
    shipped: '#67C23A',
    completed: '#909399',
    cancelled: '#F56C6C'
  }
  return colorMap[status] || '#909399'
}

// 获取订单状态步骤
const getStatusStep = (status) => {
  const stepMap = {
    pending: 0,
    paid: 1,
    shipped: 2,
    completed: 3,
    cancelled: 0
  }
  return stepMap[status] || 0
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    alipay: '支付宝',
    wechat: '微信支付',
    unionpay: '银联支付'
  }
  return methodMap[method] || method
}

// 复制订单号
const copyOrderId = () => {
  navigator.clipboard.writeText(order.value.orderId).then(() => {
    ElMessage.success('订单号已复制')
  })
}

// 复制物流单号
const copyTrackingNumber = () => {
  navigator.clipboard.writeText(order.value.logistics.trackingNumber).then(() => {
    ElMessage.success('物流单号已复制')
  })
}

// 立即付款
const handlePay = () => {
  router.push({
    path: '/home/checkout',
    query: { orderId: order.value.orderId }
  })
}

// 确认收货
const handleConfirmReceive = () => {
  ElMessageBox.confirm('确认已收到商品？', '确认收货', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API确认收货
    ElMessage.success('确认收货成功')
  })
}

// 评价
const handleReview = () => {
  router.push({
    path: '/home/orders',
    query: {
      orderId: order.value.orderId,
      action: 'review'
    }
  })
}

// 取消订单
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.put(`/orders/${order.value.id}/cancel`)
    if (res.code === 200) {
      ElMessage.success('订单取消成功')
      fetchOrderDetail() // 刷新订单详情
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 申请退款
const handleRefund = async () => {
  try {
    await ElMessageBox.confirm('确定要申请退款吗？退款将在3-5个工作日内到账。', '申请退款', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.post(`/orders/${order.value.id}/refund`)
    if (res.code === 200) {
      ElMessage.success('退款申请已提交，请耐心等待处理')
      fetchOrderDetail() // 刷新订单详情
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('申请退款失败:', error)
      ElMessage.error('申请退款失败')
    }
  }
}

// 页面初始化
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.status-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.status-text {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-info h2 {
  margin: 0 0 5px;
  font-size: 20px;
}

.status-info p {
  margin: 0;
  color: #909399;
}

.status-steps {
  margin-top: 30px;
}

.section-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-title {
  margin: 0 0 20px;
  font-size: 16px;
  font-weight: bold;
}

.delivery-info,
.payment-info,
.order-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  color: #909399;
  width: 100px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.product-detail {
  flex: 1;
}

.product-name {
  margin-bottom: 5px;
}

.product-specs {
  color: #909399;
  font-size: 14px;
}

.subtotal {
  color: #F56C6C;
  font-weight: bold;
}

.payment-info {
  display: flex;
  justify-content: space-between;
}

.info-group {
  flex: 1;
}

.amount-info {
  text-align: right;
  min-width: 300px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.amount-item.total {
  border-top: 1px solid #EBEEF5;
  padding-top: 10px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: bold;
}

.amount-item .price {
  color: #F56C6C;
  font-size: 20px;
}

.logistics-header {
  margin-bottom: 20px;
}

.logistics-timeline {
  margin-top: 20px;
  padding-left: 20px;
}

.empty-logistics {
  color: #909399;
  text-align: center;
  padding: 30px 0;
}
</style>